import ast
import json
import os.path
import uuid

import pandas as pd
import yaml

from core.globalContext import g_context

# 先加载context.xlsx文件中的数据 保存为环境变量
def load_context_from_excel(folder_path):
    try:
        # 读取excel中context路径
        excel_file_path = os.path.join(folder_path, 'context.xlsx')
        # 读取excel_file_path文件数据
        df = pd.read_excel(excel_file_path)
        # 把context中的数据放在字典中
        data = {
            "_database": {}
        }
        # 循环df中的数据
        # index 0,1,2  row是excel中具体行的值
        for index, row in df.iterrows():
            if row['类型'] == '变量':
                data[row['变量描述']] = row['变量值']
            elif '数据库' in row['类型']:
                db_name = row['变量描述']  # 数据库
                db_config = json.loads(row['变量值']) # loads() 把json字符串转换为dict对象
                data["_database"][db_name] = db_config
            if data: g_context().set_by_dict(data)
            # print(data)
    except Exception as e:
        print(f"装着excel文件错误:{str(e)}")


# 读取多个excel数据
def load_excel_files(folder_path):
    # 调用读取context.excel的函数
    excel_caseinfos = []
    load_context_from_excel(folder_path)
    file_names = []
    # 拿到excel目录中的所有文件和子文件
    allfiles = os.listdir(folder_path)
    for f in allfiles:
        # 规则，必须以.xlsx结尾，第一个是数字用_分割
        if f.endswith(".xlsx") and f.split("_")[0].isdigit():
            file_number = int(f.split("_")[0])
            file_names.append((file_number, f))  # [(1,1_test_hc_shop.xlsx),(2,3_addcard_yaml.yaml)]
    file_names.sort()
    file_names = [f[1] for f in file_names]

    current_dir = os.path.abspath(os.path.dirname(__file__))
    parent_dir = os.path.dirname(current_dir)
    keywords_file_path = os.path.join(parent_dir, "extend/keywords.yaml")

    # 把keyword的值做为键
    keywords_info = {}
    with open(keywords_file_path, 'r', encoding="utf-8") as f:
        keywords_info = yaml.full_load(f)
        # print("keywords.yaml文件中的数据", keywords_info) # {'request_post_form_data': ['URL', 'PARAMS', 'HEADERS', 'DATA']}
        # excel中的数据  读取excel中的数据做为值
        for file_name in file_names:
            # 具体一个excel路径
            file_path = os.path.join(folder_path, file_name)
            # 读取excel数据
            data = pd.read_excel(file_path, sheet_name=0,dtype=object)
            # 把data中的所有空值设置为None
            data = data.where(data.notnull(), None)
            # 把excel转为字典
            data = data.to_dict("records")
            # print("excel中所有数据",data)

            # 定义一条用例的变量   [{},{},{}]
            current_test_case = None
            # 对于每条用例数据处理
            for row in data:
                if pd.notna(row["测试用例标题"]):
                    # 检查有没有用例标题是none None就添加current_test_case
                    if current_test_case is not None:  # 已经构造好一个用例对象
                        excel_caseinfos.append(current_test_case)
                    current_test_case = {"desc": row['测试用例标题'], "step": []}
                # 处理step
                steps = {
                    row['步骤描述']: {'关键字': row['关键字']}
                }
                # print("处理steps", steps)
                param = []
                for key, value in row.items():
                    if '参数_' in key:
                        try:
                            value = ast.literal_eval(value)
                        except Exception as e:
                            pass
                        param.append(value)
                # print("处理param", param)
                # keywords.yaml做为键   param做为值
                # {url:xxx,PARAMS:xx}
                dict_param = {k: v for k, v in zip(keywords_info[row['关键字']], param)}
                # print("数据", dict_param)
                steps[row["步骤描述"]].update(dict_param)
                current_test_case['step'].append(steps)
                # print("组装好的用例", current_test_case)

            if current_test_case is not None:
                excel_caseinfos.append(current_test_case)
    return excel_caseinfos


# 统一后续yaml/excel的数据格式
def excel_case_parser(folder_path):
    case_infos = []
    case_names = []
    excel_caseinfos = load_excel_files(folder_path)
    for caseinfo in excel_caseinfos:
        case_name = caseinfo.get("desc", uuid.uuid4().__str__())
        caseinfo.update({"_case_name": case_name})
        case_infos.append(caseinfo)
        case_names.append(case_name)
    return {
        "case_info": case_infos,
        "case_name": case_names
    }


if __name__ == '__main__':
    a = load_excel_files(r'D:\API\examples\excel_testcase')
    print("所有数据", a)

# 读取excel线性代码
# def read_Excel(filename):
#     df=pd.read_excel(filename)
#     print("读取excel数据",df)
#     row_to_dict=df.to_dict("records")
#     print("转成字典数据",row_to_dict)
#     row_to_list = df.values.tolist()
#     print("转成列表数据", row_to_list)
#     return (row_to_dict)
# data={
#   name:['Alice','bob']
#   age:[25,30]
# }
# {name:'Alice',age:'25'}
#  测试
# if __name__ == '__main__':
#     r=read_Excel(r'E:\hcVip\info\hc_vip_project\day13\examples\excel_testcase\testcaselogin.xlsx')
#     print(r)
